package no.progark.helikopter;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.Animation;


public class Panel extends SurfaceView implements SurfaceHolder.Callback {
    private GameThread _thread;
    private ArrayList<GraphicObject> _graphics = new ArrayList<GraphicObject>();

    public Panel(Context context) {
        super(context);
        System.out.println("heidsfsdfdsfsdfsd!!");
        getHolder().addCallback(this);
        _thread = new GameThread(getHolder(), this);
        setFocusable(true); 
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        synchronized (_thread.getSurfaceHolder()) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                GraphicObject graphic = new GraphicObject(BitmapFactory.decodeResource(getResources(), R.drawable.copter));
                graphic.getCoordinates().setX((int) event.getX() - graphic.getGraphic().getWidth() / 2);
                graphic.getCoordinates().setY((int) event.getY() - graphic.getGraphic().getHeight() / 2);
                _graphics.add(graphic);
            }
            return true;
        }
    }

    @Override
    public void onDraw(Canvas canvas) {
        canvas.drawColor(Color.BLUE);
        Bitmap bitmap;
        GraphicObject.Coordinates coords;
        for (GraphicObject graphic : _graphics) {
            bitmap = graphic.getGraphic();
            coords = graphic.getCoordinates();
            canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
        }
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // TODO Auto-generated method stub
    }

    public void surfaceCreated(SurfaceHolder holder) {
        _thread.setRunning(true);
        _thread.start();
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // simply copied from sample application LunarLander:
        // we have to tell thread to shut down & wait for it to finish, or else
        // it might touch the Surface after we return and explode
        boolean retry = true;
        _thread.setRunning(false);
        while (retry) {
            try {
                _thread.join();
                retry = false;
            } catch (InterruptedException e) {
                // we will try it again and again...
            }
        }
    }
}